
// atv.Document extensions
if(atv.Document)
{
	atv.Document.prototype.getElementById = function(id)
	{
		var elements = this.evaluateXPath("//*[@id='" + id + "']", this);
		return (elements && elements.length > 0) ? elements[0] : undefined;
	};
}

//
if(atv.Element)
{
	atv.Element.prototype.getElementsByTagName = function(name)
	{
		return this.ownerDocument.evaluateXPath("descendant::" + name, this);
	};
	atv.Element.prototype.getElementByTagName = function(name)
	{
		var elements = this.getElementsByTagName(name);
		return (elements && elements.length > 0) ? elements[0] : undefined;
	};
}

//
function quoteXML(s)
{
	return s.replace(/[&<>'"]/g, function(c)
	{
		return "&" + {
			"&": "amp",
			"<": "lt",
			">": "gt",
			"'": "apos",
			'"': "quot"
		}[c] + ";"
	})
}

//
function makeXML(body, head)
{
	var xml = '<?xml version="1.0" encoding="UTF-8"?><atv>' + (head ? ('<head>' + head + '</head>') : '') + '<body>' + body + '</body></atv>';
	return atv.parseXML(xml);
}

//
function makeError(msg, desc)
{
	return makeXML('<dialog id="error"><title><![CDATA[' + (msg || '') + ']]></title><description><![CDATA[' + (desc || '') + ']]></description></dialog>');
}

//
var mediaParser =
{
	splitText: function(text)
	{
		var blocks = text.split('</tr>');
		if(blocks.length < 2) blocks = text.split('</li>');
		if(blocks.length < 2) blocks = text.split('<br>');
		return blocks;
	},

	parseBlock: function(block, host, base, sbase)
	{
		var re = new RegExp('<a href="(.*?)">(.*?)</a>', 'i');
		var rs = re.exec(block);
		if(rs)
		{
			var href = rs[1];
			var name = rs[2].replace(/^\s+/,'').replace(/\s+$/,'');	// Trim prefix and sufix space

			// Make full href
			var url;
			if(href.indexOf(':') == -1)
			{
				if(href.charAt(0) == '/') url = host + href;
				else url = base + href;
			}
			else
			{
				url = href;
			}
			
			if ((name.charAt(0) != '.') &&
				//(href.indexOf('?') == -1) &&
				(name.indexOf('Parent Directory') == -1))
			{
				// Determine type
				var type;
				if(href.charAt(href.length - 1) == '/')
				{
					type = 'dir';

					if(name.charAt(name.length - 1) == '/') name = name.substring(0, name.length - 1);
				}
				else
				{
					type = href.substring(href.lastIndexOf('.') + 1).toLowerCase();

					// Make name without extsion
					var pos = name.lastIndexOf('.');
					if(pos != -1) name = name.substring(0, pos);
				}

				var image = this.fetchThumb(href) || (sbase +'image/' + type + '.png');
				return [type, url, name, image];
			}
			else
			{
				this.pushThumb(url);
			}
		}
		return null;
	},

	// Push to thumbs array
	pushThumb: function(url)
	{
		if(url.indexOf('.thumb.') != -1)
		{
			if (this.thumbs)
			{
				this.thumbs.push(url);
			}
			else
			{
				this.thumbs = [url];
			}
		}
	},

	// Fetch from thumbs array
	fetchThumb: function(href)
	{
		var name = (href.charAt(href.length - 1) == '/') ? href.substring(0, href.length - 1) : href;
		for (var i in this.thumbs)
		{
			if(this.thumbs[i].indexOf(name) != -1)
			{
				return this.thumbs[i];
			}
		}
	},
};

//
function makeMedia(url, text)
{
	// 
	var surl = document.rootElement.getElementByTagName("script").getAttribute('src');
	var sbase = surl.substring(0, surl.lastIndexOf('/') + 1);
	var base = url.substring(0, url.lastIndexOf('/') + 1);
	var host = url.substring(0, url.indexOf('/', 8));

	// 
	var posters = [];
	var photos = [];
	if(text != null)
	{
		// Split text to blocks
		var blocks = mediaParser.splitText(text);
		var param = (url.indexOf('reverse=always') != -1) ? '?reverse=always' : '';

		// Geenrate item
		for(var i in blocks)
		{
			var rs = mediaParser.parseBlock(blocks[i], host, base, sbase);
			if(rs)
			{
				var type = rs[0];
				var href = rs[1];
				var name = rs[2];
				var image = rs[3];

				// Geenrate item
				if(type == 'dir' || type == 'mov' || type == 'mp4' || type == 'm4v' || type == 'mpg' || type == 'avi' || type == 'm3u' || type == 'mp3' || type == 'aac')
				{
					var id = type + posters.length;
					var action = 'loadPage(\'' + quoteXML(href) + ((type == 'dir') ? param : '') + '\')';
					
					var poster = '<moviePoster alwaysShowTitles="true" id="' + id + '" onPlay="' + action + '" onSelect="' + action + '">';
					poster += '<title>' + quoteXML(name) + '</title>';
					poster += '<image>' + quoteXML(image) + '</image>';
					poster += '<defaultImage>resource://Poster.png</defaultImage>';
					poster += '</moviePoster>';
					posters.push(poster);
				}
				else if(type == 'jpg' || type == 'png' || type == 'gif' || type == 'bmp')
				{
					var id = type + photos.length;
					var photo = '<photo id="' + id + '" onSelect="onPhotoSelection(\'' + id + '\')" onPlay="onSlideshowStart(\'' + id + '\')">';
					photo += '<assets><photoAsset width="486" height="720" src="' + quoteXML(href) + '"/></assets>';
					photo += '</photo>';
					photos.push(photo);
				}
			}
		}
	}

	//
	if(photos.length == 0 && posters.length == 0)
	{
		return makeError('没有内容', decodeURIComponent(url));
	}

	// Geenrate XML
	var body;
	var head = '<script id="media.js" src="' + sbase + 'media.js"/>';
	if(photos.length > posters.length)
	{
		if((url.indexOf('reverse=') != -1)) photos = photos.reverse();

		var temp = (url.charAt(url.length - 1) == '/') ? url.substring(0, url.length - 1) : url;
		var title = decodeURIComponent(temp.substring(temp.lastIndexOf('/') + 1));

		head += '<script src="' + sbase + 'slide.js"/>';
		body = '<mediaBrowser id="browser" gridLayout="mixed">';
		body += '<header><headerWithCountAndButtons><title>' + title + '</title><count>' + photos.length + '</count>';
		body += '<buttons><actionButton id="slideshow" onSelect="onSettingsSelection()" onPlay="onSlideshowStart()"><title>幻灯片播放</title></actionButton></buttons>';
		body += '</headerWithCountAndButtons></header><items>' + photos.join('\n') + '</items></mediaBrowser>';
	}
	else
	{
		if((url.indexOf('reverse=') != -1)) posters = posters.reverse();

		body = '<scroller id="scroller"><items><grid columnCount="5" id="grid"><items>' + posters.join('\n') + '</items></grid></items></scroller>';
	}

	return makeXML(body, head);
}

//
function loadDoc(doc, event)
{
	if (event) event.success(doc);
	else atv.loadXML(doc);
}

//
function loadPage(url, event)
{
	// Load player
	var type = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
	if(type == 'mov' || type == 'mp4' || type == 'm4v' || type == 'mpg' || type == 'avi' || type == 'm3u' || type == 'mp3' || type == 'aac')
	{
		loadDoc(makeXML('<videoPlayer id="player"><httpFileVideoAsset id="asset"><mediaURL>' + url + '</mediaURL></httpFileVideoAsset></videoPlayer>'), event);
		return;
	}

	// Request page
	var req = new XMLHttpRequest();
	req.onreadystatechange = function()
	{
		try
		{
			if(req.readyState == 4)
			{
				loadDoc((req.status == 200) ? ((url.indexOf('.xml') != -1) ? req.responseXML : makeMedia(url, req.responseText)) : makeError('状态错误：' + req.status, url), event);
			}
		}
		catch(e)
		{
			req.abort();
			loadDoc(makeError(e, url), event);
		}
	}
	req.open('GET', url, true);
	req.send();
}

//
function loadItem(event)
{
	var id = event.navigationItemId;
	var item = document.getElementById(id);
	var url = item.getElementByTagName('url').textContent;
	loadPage(url, event);
}
